<template>
    <div style="margin-top: 30px" v-loading="fullFormLoading">
        <el-form label-width="14%" style="display: grid;gap: 16px;grid-template-columns: repeat(4, 1fr);">
            <el-form-item label="实例ID">
                <el-input v-model="searchFlowInstanceId" placeholder="实例ID"></el-input>
            </el-form-item>
            <el-form-item label="版本">
                <el-select v-model="currentVersion" placeholder="版本" @change="versionSelectChange()">
                    <el-option :label="item.innerName" :value="item.version" v-for="item in versionList" :key="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="实例状态">
                <el-select v-model="flowStatus" placeholder="实例状态">
                    <el-option label="启动中" value="STARTING"/>
                    <el-option label="运行中" value="RUNNING"/>
                    <el-option label="执行完成" value="FINISH"/>
                    <el-option label="执行异常" value="EXCEPTION"/>
                </el-select>
            </el-form-item>
            <el-form-item v-for="(item, index) in formConditionList" :label="item.labelName">
                <component :is="components[item.component]" :isEdit="false" :isInstanceSearch="true" :properties="item" :formBuildList="formBuildList"/>
            </el-form-item>
        </el-form>
        <div class="formSubmitButton">
            <el-button @click="addFormInstanceCondition()">添加条件</el-button>
            <el-button type="primary" :loading="searchLoading" @click="searchClick()">查 询</el-button>
        </div>
    </div>

    <div style="padding-left: 20px; padding-right: 20px; margin-top: 50px" v-loading="flowTableLoading">
        <el-table
            :data="flowInstanceDataList"
            style="width: 100%;"
            row-key="id"
            border
            :stripe="true"
            :show-overflow-tooltip="true"
            class="tableContainer"
            max-height="70vh"
            v-if="reloadTable"
        >
            <el-table-column v-for="item in tableItemList" :key="item.prop" :prop="item.prop" :label="item.label" >
                <template #default="scope" v-if="item.prop === 'status'">
                    <el-tag type="success" v-if="scope.row.status === 'FINISH'">流程结束</el-tag>
                    <el-tag type="primary" v-if="scope.row.status === 'RUNNING'">流程运行中</el-tag>
                    <el-tag type="warning" v-if="scope.row.status === 'STARTING'">流程启动中</el-tag>
                    <el-tag type="danger" v-if="scope.row.status === 'EXCEPTION'">流程异常</el-tag>
                </template>
            </el-table-column>

            <el-table-column align="center" width="200px">
                <template #header>
                    <span>操 作</span>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <div style="padding-right: 20px;">
        <el-pagination
            v-model:current-page="pageIndex"
            v-model:page-size="pageSize"
            layout="prev, pager, next, jumper, sizes, total"
            :background="true"
            :total="recordCount"
            style="margin-top: 30px;width: 100%;display: flex; align-items: center;justify-content: right"
            @change="changePage"
            :page-sizes="[10, 20, 30, 40, 50]"
        />
    </div>

    <div>
        <el-dialog
            v-model="isConditionShowDrawer"
            title="编辑表单实例条件"
            :show-close="false"
            :width="600"
            :close-on-click-modal="false"
        >
            <el-transfer class="formSubmitButton" :data="conditionSourceList" v-model="conditionTargetList"
                         :titles="['表单组件', '条件']"/>
            <div class="formSubmitButton" style="margin-top: 30px">
                <el-button @click="cancelFormInstanceCondition()">取消</el-button>
                <el-button @click="commitFormInstanceCondition()" :loading="conditionInstanceLoading" type="primary">提交</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup name="FormInstanceList">
import YwuFormInput from "@/views/bpmn/form/component/YwuFormInput.vue";
import YwuFormSelect from "@/views/bpmn/form/component/YwuFormSelect.vue";
import YwuFormCascaderSelect from "@/views/bpmn/form/component/YwuFormCascaderSelect.vue";
import YwuFormCheckBox from "@/views/bpmn/form/component/YwuFormCheckBox.vue";
import YwuFormDate from "@/views/bpmn/form/component/YwuFormDate.vue";
import YwuFormInputNumber from "@/views/bpmn/form/component/YwuFormInputNumber.vue";
import YwuFormRadio from "@/views/bpmn/form/component/YwuFormRadio.vue";
import YwuFormRate from "@/views/bpmn/form/component/YwuFormRate.vue";
import YwuFormSwitch from "@/views/bpmn/form/component/YwuFormSwitch.vue";
import YwuFormTime from "@/views/bpmn/form/component/YwuFormTime.vue";
import YwuFormTreeSelect from "@/views/bpmn/form/component/YwuFormTreeSelect.vue";
import YwuFormUploadFile from "@/views/bpmn/form/component/YwuFormUploadFile.vue";
import YwuFormUploadImage from "@/views/bpmn/form/component/YwuFormUploadImage.vue";
import {
    createFormInstanceCondition,
    queryFlowInstanceList, queryFlowVersionFormInfo, queryFlowVersionInfo,
    queryFlowVersionList, queryFormInstanceCondition,
} from "@/request/flow";
import {ElNotification} from "element-plus";
import {onMounted, ref} from "vue";
import {useRoute, useRouter} from "vue-router";

let route = useRoute();
let router = useRouter();

// 显式声明组件变量（确保被引用）
const components = { YwuFormInput, YwuFormSelect, YwuFormCascaderSelect, YwuFormCheckBox, YwuFormDate,
    YwuFormInputNumber, YwuFormRadio, YwuFormRate, YwuFormSwitch, YwuFormTime, YwuFormTreeSelect, YwuFormUploadFile, YwuFormUploadImage };

let currentVersion = ref(0);
let versionList = ref([]);
let globalProperties = ref({
        colNum: 1
    });
let formBuildList = ref([]);
let searchFlowInstanceId = ref("");
let flowInstanceDataList = ref([]);
let tableItemList = ref([]);
let reloadTable = ref(true);
let pageIndex = ref(1);
let pageSize = ref(10);
let recordCount = ref(0);
let searchLoading = ref(false);
let formConditionList = ref([]);
let isConditionShowDrawer = ref(false);
let conditionInstanceLoading = ref(false);
let conditionSourceList = ref([]);
let conditionTargetList = ref([]);
let fullFormLoading = ref(false);
let flowTableLoading = ref(false);
let flowStatus = ref("");
let formId = ref("");

function buildTableItem() {
    tableItemList.value = [];
    tableItemList.value[0] = {label: "实例ID", prop: "id"};
    tableItemList.value[1] = {label: "实例版本", prop: "flowVersion"};
    tableItemList.value[2] = {label: "实例状态", prop: "status"};
    for (let index = 0; index < formBuildList.value.length; index++) {
        let itemInfo = formBuildList.value[index]
        tableItemList.value[index + 3] = {label: itemInfo.labelName, prop: itemInfo.code};
    }
}

function queryInstanceList(param) {
    queryFlowInstanceList(param).then(res => {
        flowInstanceDataList.value = [];
        for (let index = 0; index < res.data.dataList.length; index++) {
            let item = res.data.dataList[index]
            let jsonStr = item.formInstanceJson;
            let jsonInfo = {
                id: item.id,
                flowVersion: item.flowVersion,
                status: item.status
            }
            let formInstanceList = JSON.parse(jsonStr);
            for (let index = 0; index < formInstanceList.length; index++) {
                jsonInfo[formInstanceList[index].code] = formInstanceList[index].value;
            }
            flowInstanceDataList.value.push(jsonInfo);
        }
        pageIndex.value = res.data.pageIndex;
        pageSize.value = res.data.pageSize;
        recordCount.value = res.data.recordCount;
        flowTableLoading.value = false;
        searchLoading.value = false;
    }).catch(res => {
        flowTableLoading.value = false;
        searchLoading.value = false;
    })
}

function queryBuildInfoAndInstanceInfo() {
    fullFormLoading.value = true;
    flowTableLoading.value = true
    let flowId = route.query.id;
    queryFlowVersionInfo({resourceId: flowId, version: currentVersion.value}).then(queryVersionRes => {
        if (queryVersionRes.code === "200") {
            // 获取表单ID
            formId.value = queryVersionRes.data.formId;
            // 根据表单ID查询表单详情
            queryFlowVersionFormInfo({resourceId: flowId, version: currentVersion.value}).then(queryFormVersionRes => {
                if (queryFormVersionRes.code === "200") {
                    let formJson = queryFormVersionRes.data.formJson
                    // 序列化json
                    let jsonInfo = JSON.parse(formJson);
                    globalProperties.value = jsonInfo.globalProperties
                    formBuildList.value = jsonInfo.componentJson
                    // 构建表单内容信息
                    buildTableItem();
                }
            })
            // 查询流程实例列表
            let param = getQueryParam();
            queryInstanceList(param);
            // 查询表单实例条件
            queryFormInstanceCondition({formId: formId.value, formVersion: currentVersion.value}).then(res => {
                formConditionList.value = []
                if (res.code === "200") {
                    if (res.data === null) {
                        formConditionList.value = []
                    } else {
                        let formConditionJson = res.data.formConditionJson
                        // 序列化json
                        formConditionList.value = JSON.parse(formConditionJson);
                    }
                }
                fullFormLoading.value = false;
            }).catch(res => {
                fullFormLoading.value = false;
            })
        }
    }).catch(res => {
        flowTableLoading.value = false;
    })
}

function versionSelectChange() {
    queryBuildInfoAndInstanceInfo();
}

function getQueryParam() {
    let flowId = route.query.id;
    let param = {
        pageInfo: {
            pageIndex: pageIndex.value,
            pageSize: pageSize.value
        },
        id: searchFlowInstanceId.value,
        flowId: flowId,
        flowVersion: currentVersion.value,
        flowStatus: flowStatus.value
    }
    let formInstanceJson = [];
    for (let index = 0; index < formConditionList.value.length; index++) {
        let itemInfo = formConditionList.value[index];
        if (!itemInfo.searchValue) {
            continue;
        }
        if (Array.isArray(itemInfo.searchValue) && itemInfo.searchValue.length === 0) {
            continue;
        }
        let searchValue = itemInfo.searchValue;
        if (typeof searchValue !== 'string') {
            searchValue = "" + searchValue
        }
        formInstanceJson.push({
            id: itemInfo.code,
            value: searchValue
        })
    }
    param.extendFormFieldList = formInstanceJson
    return param;
}

function searchClick() {
    searchLoading.value = true;
    // 查询数据
    let param = getQueryParam()
    queryInstanceList(param);
}

function cancelFormInstanceCondition() {
    isConditionShowDrawer.value = false;
}

function commitFormInstanceCondition() {
    conditionInstanceLoading.value = true;
    // 调用接口保存条件信息
    let param = {
        formId: formId.value,
        formVersion: currentVersion.value,
    }
    let formConditionJsonInfo = []
    // 将target中的对象添加到参数中
    for (let index = 0; index < conditionTargetList.value.length; index++) {
        let itemId = conditionTargetList.value[index]
        for (let innerIndex = 0; innerIndex < formBuildList.value.length; innerIndex++) {
            if (formBuildList.value[innerIndex].id === itemId) {
                formConditionJsonInfo.push(formBuildList.value[innerIndex])
                break;
            }
        }
    }
    param.formConditionJson = JSON.stringify(formConditionJsonInfo);
    // 调用方法创建表单条件
    createFormInstanceCondition(param).then(res => {
        if (res.code === "200") {
            ElNotification({
                title: 'Success',
                message: res.message,
                type: 'success',
            })
            queryFormInstanceCondition({formId: formId.value, formVersion: currentVersion.value}).then(res => {
                formConditionList.value = []
                if (res.code === "200") {
                    if (res.data === null) {
                        formConditionList.value = []
                    } else {
                        let formConditionJson = res.data.formConditionJson
                        // 序列化json
                        formConditionList.value = JSON.parse(formConditionJson);
                    }
                }
                conditionInstanceLoading.value = false;
                isConditionShowDrawer.value = false;
            }).catch(res => {
                conditionInstanceLoading.value = false;
                isConditionShowDrawer.value = false;
            })
        }
    }).catch(res => {
        conditionInstanceLoading.value = false;
        isConditionShowDrawer.value = false;
    })
}

function addFormInstanceCondition() {
    conditionSourceList.value = []
    conditionTargetList.value = []
    for (let index = 0; index < formBuildList.value.length; index++) {
        conditionSourceList.value.push({
            key: formBuildList.value[index].id,
            label: formBuildList.value[index].labelName
        })
    }
    // 构建出当前已经存在的所有id列表
    for (let index = 0; index < formConditionList.value.length; index++) {
        conditionTargetList.value.push(formConditionList.value[index].id)
    }
    isConditionShowDrawer.value = true;
}

function changePage() {
    // 查询数据
    let param = getQueryParam()
    queryInstanceList(param)
}

onMounted(() => {
    fullFormLoading.value = true;
    flowTableLoading.value = true
    // 根据表单ID查询当前表单最新版本以及表单的构建信息
    let flowId = route.query.id;
    queryFlowVersionList({id: flowId}).then(res => {
        if (res.code === "200") {
            let dataInfo = res.data;
            if (dataInfo.length === 0 || (dataInfo.length === 1 && dataInfo[0].version === 0)) {
                ElNotification({
                    title: 'Error',
                    message: "不存在可用发布版本",
                    type: 'error',
                })
                fullFormLoading.value = false;
                flowTableLoading.value = false
                return
            }
            // 获取最新版本
            if (dataInfo[0].version === 0) {
                currentVersion.value = dataInfo[1].version;
            } else {
                currentVersion.value = dataInfo[0].version;
            }
            // 获取版本下拉列表
            let tempList = dataInfo
            if (tempList[0].version === 0) {
                tempList.splice(0, 1);
            }
            versionList.value = tempList;
            // 为每个版本对象添加一个内置名称
            for (let index = 0; index < versionList.value.length; index++) {
                versionList.value[index].innerName = "版本" + versionList.value[index].version;
            }
            // 查询表单对应的构建信息以及表单对应的实例信息
            queryBuildInfoAndInstanceInfo();
        }
    }).catch(res => {
        fullFormLoading.value = false;
        flowTableLoading.value = false
    })
})
</script>

<style scoped lang="less">
.formSubmitButton {
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>